<template>
  <div class="avatar-uploader">
    <el-button type="primary" @click="uploadTips" v-show="showUpload">点击上传</el-button>
    <el-upload
      v-show="!showUpload"
      border
      action="api/upload-file"
      :data="uploadType"
      name="file"
      :headers="myHeaders"
      :show-file-list="false"
      :on-preview="onPreview"
      :on-success="onSuccess"
      :on-progress="onProgress"
      :before-upload="beforeUpload"
      :limit="limit"
      ref="upload"
    >
    </el-upload>
    <div
      class="loading-box"
      v-if="loading"
      v-loading="loading"
      element-loading-text="文件过大的话，可能时间需要久一点，请耐心等待哦~~"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    ></div>
  </div>
</template>

<script>
export default {
  name: "MyUploader",
  props: {
    //组件唯一标识
    uploadId: {
      type: String,
      default() {
        return "cropperWithUpload";
      },
    },
    uploadType: {
      default() {
        return {
          type: 1,
        };
      },
      type: Object,
    },
    filePath: {
      default() {
        return '';
      },
      type: String,
    },
    fileList: {
      default() {
        return [];
      },
      type: Array,
    },
    limit: {
      default() {
        return 1;
      },
      type: Number,
    },
  },
  data() {
    return {
      myHeaders: {
        Accept: "application/json",
        Authorization: "Bearer  " + localStorage.getItem("token"),
      },
      dialogImageUrl: "",
      loading: false,
      showUpload: true,
    };
  },
  methods: {
    onChange(files, fileList) {},
    onRemove() {
      this.$emit("removeFile", {
        uploadId: this.uploadId,
        fileList: [],
      });
    },
    beforeUpload(file){

    },
    uploadTips(){
      if(this.filePath){
        this.$confirm('文件已上传，重新上传将覆盖源文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs['upload'].$refs['upload-inner'].handleClick() //触发上传组件中的按钮点击事件
          return true
        }).catch(() => {
          return false     
        });
      } else {
        this.$refs['upload'].$refs['upload-inner'].handleClick() 
      }
    },
    onPreview(file) {
      console.log(file)
    },
    onProgress(file) {
      this.loading = true;
    },
    onSuccess(response, file, fileList) {
      this.$refs.upload.clearFiles()
      this.loading = false;
      this.$emit("uploadFile", {
        uploadId: this.uploadId,
        fileList: file.response.data,
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader {
  width: 98px;
  height: 40px;
  display: inline-block;
}
.loading-box {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 999;
  left: 0;
  top: 0;
}
.loading-box >>>.el-icon-loading{
  font-size: 50px;
}
</style>
